<template>
  <view class="imt-audio">
    <view class="top">
      <view class="audio-control-wrapper">
        <!-- 封面图 -->
        <image :src="poster" mode="aspectFill" class="cover"></image>
        <!-- 加载中图标 -->
        <image :src="require('./static/loading.png')" v-if="playState === 'loading'" class="play loading"></image>
        <!-- 播放/暂停按钮 -->
        <template v-else>
          <image :src="require('./static/playbtn.png')" alt="play" @click="play" class="play" v-if="playState === 'pause'"></image>
          <image :src="require('./static/pausebtn.png')" alt="pause" @click="pause" class="play" v-else></image>
        </template>
      </view>
    </view>
    <view class="audio-wrapper">
      <view class="titlebox">
        <view class="title">{{ name }}</view>
        <view class="singer">{{ singer }}</view>
      </view>
      <view class="slidebox">
        <view>{{ formatSeconds(currentTime) }}/{{ formatSeconds(duration) }}</view>
        <view class="speed-control">
          <!-- 倍速选择器 -->
          <picker mode="selector" :range="speedOptions" :value="selectedSpeedIndex" @change="handleSpeedChange">
            <text class="speed-text">{{ speedOptions[selectedSpeedIndex] }}</text>
          </picker>
          <!-- 额外按钮插槽 -->
          <slot name="extraCtrls">
            <text class="hItem extrButton" @click="$emit('Button1Click')" v-show="isButton1Visible">{{ button1Text }}</text>
            <text class="hItem extrButton" @click="$emit('Button2Click')" v-show="isButton2Visible">{{ button2Text }}</text>
            <text class="hItem extrButton" @click="$emit('Button3Click')" v-show="isButton3Visible">{{ button3Text }}</text>
          </slot>
        </view>
      </view>
      <!-- 进度条 -->
      <slider class="audio-slider" block-size="12" :max="duration" :value="currentTime" @change="sliderChange" @changing="sliderChanging" />
    </view>
    <!-- 音频播放核心组件 (隐藏) -->
    <video
      id="videoPlayer"
      :src="src"
      autoplay="false"
      :muted="false"
      style="width: 1px; height: 1px; position: absolute; top: -9999px"
      @play="playerOnPlay"
      @pause="playerOnPause"
      @ended="playerOnEnded"
      @timeupdate="playerOnTimeupdate"
      @waiting="playerOnWaiting"
      @error="playerOnError"
      @loadedmetadata="playerOnLoadedMetadata"
    ></video>
  </view>
</template>

<script>
export default {
  props: {
    // 音频源地址 (必填)
    src: {
      type: String,
      required: true,
    },
    // 歌曲名称
    name: {
      type: String,
      default: '未知歌曲',
    },
    // 歌手名称
    singer: {
      type: String,
      default: '未知歌手',
    },
    // 封面图地址
    poster: {
      type: String,
      default: '',
    },
    // 额外按钮1
    isButton1Visible: {
      type: Boolean,
      default: false,
    },
    button1Text: {
      type: String,
      default: '',
    },
    // 额外按钮2
    isButton2Visible: {
      type: Boolean,
      default: false,
    },
    button2Text: {
      type: String,
      default: '',
    },
    // 额外按钮3
    isButton3Visible: {
      type: Boolean,
      default: false,
    },
    button3Text: {
      type: String,
      default: '',
    },
  },
  data() {
    return {
      duration: 0, // 总时长
      currentTime: 0, // 当前播放时间
      playState: 'pause', // 播放状态: "loading", "playing", "pause"
      isSliderChanging: false, // 进度条是否正在被拖动
      
      // 倍速播放
      speedOptions: ['0.5X', '1.0X', '1.25X', '1.5X', '2.0X'],
      selectedSpeedIndex: 1, // 默认1.0X
    };
  },
  onReady() {
    // 在组件渲染完成后，创建 video 上下文
    this.videoCtx = uni.createVideoContext('videoPlayer', this);
  },
  methods: {
    /**
     * 音频元数据加载完成时触发 (可获取总时长)
     */
    playerOnLoadedMetadata(e) {
      this.duration = e.detail.duration;
    },

    /**
     * 播放时触发
     */
    playerOnPlay(e) {
      this.playState = 'playing';
      this.$emit('play', e);
    },

    /**
     * 暂停时触发
     */
    playerOnPause(e) {
      this.playState = 'pause';
      this.$emit('pause', e);
    },

    /**
     * 播放结束时触发
     */
    playerOnEnded(e) {
      this.playState = 'pause';
      this.$emit('ended', e);
    },

    /**
     * 播放时间更新时触发
     */
    playerOnTimeupdate(e) {
      if (!this.isSliderChanging) {
        this.currentTime = e.detail.currentTime;
        this.$emit('timeUpdate', e.detail);
      }
    },

    /**
     * 音频加载中时触发
     */
    playerOnWaiting(e) {
      this.playState = 'loading';
    },

    /**
     * 播放出错时触发
     */
    playerOnError(e) {
      uni.showToast({
        title: `播放出错: ${e.detail.errMsg}`,
        icon: 'none',
      });
      this.playState = 'pause';
      this.$emit('error', e);
    },

    /**
     * 格式化秒数为 MM:SS 格式
     */
    formatSeconds(seconds) {
      const result = typeof seconds === 'string' ? parseFloat(seconds) : seconds;
      if (isNaN(result) || result < 0) return '00:00';
      
      const minutes = Math.floor(result / 60);
      const secondsRemainder = Math.floor(result % 60);
      
      const formattedMinutes = minutes.toString().padStart(2, '0');
      const formattedSeconds = secondsRemainder.toString().padStart(2, '0');
      
      return `${formattedMinutes}:${formattedSeconds}`;
    },

    /**
     * 播放
     */
    play() {
      this.videoCtx.play();
    },

    /**
     * 暂停
     */
    pause() {
      this.videoCtx.pause();
    },

    /**
     * 停止 (复位到开头)
     */
    stop() {
      this.videoCtx.stop();
    },

    /**
     * 跳转到指定时间
     */
    seek(time) {
      this.videoCtx.seek(time);
    },

    /**
     * 处理倍速切换
     */
    handleSpeedChange(e) {
      const index = parseInt(e.detail.value);
      this.selectedSpeedIndex = index;
      
      const speed = parseFloat(this.speedOptions[index]);
      const isPlaying = this.playState === 'playing';

      // 切换倍速的兼容逻辑
      if (isPlaying) {
        this.videoCtx.pause();
      }
      
      setTimeout(() => {
        this.videoCtx.playbackRate(speed);
        if (isPlaying) {
          this.videoCtx.play();
        }
      }, 100);
    },

    /**
     * 进度条拖动结束时
     */
    sliderChange(e) {
      this.isSliderChanging = false;
      const value = e.detail.value;
      this.seek(value); // 调用seek方法跳转
    },

    /**
     * 进度条拖动过程中
     */
    sliderChanging() {
      this.isSliderChanging = true;
    },
  },
};
</script>

<style lang="scss">
/* 引入外部样式文件，如果有的话 */
/* @import './index.scss'; */

.imt-audio {
  padding: 20rpx;
  background-color: #f7f7f7;
  border-radius: 16rpx;
}

.top {
  margin-bottom: 20rpx;
}

.audio-control-wrapper {
  position: relative;
  width: 120rpx;
  height: 120rpx;
  border-radius: 50%;
  overflow: hidden;
  background-color: #eee;

  .cover {
    width: 100%;
    height: 100%;
  }

  .play {
    position: absolute;
    width: 40rpx;
    height: 40rpx;
    bottom: 10rpx;
    right: 10rpx;
    background-color: rgba(0, 0, 0, 0.5);
    border-radius: 50%;
    padding: 8rpx;
  }

  .loading {
    animation: spin 1.5s linear infinite;
  }
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

.audio-wrapper {
  .titlebox {
    margin-bottom: 10rpx;
    .title {
      font-size: 30rpx;
      font-weight: bold;
      color: #333;
    }
    .singer {
      font-size: 24rpx;
      color: #666;
    }
  }

  .slidebox {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 24rpx;
    color: #999;
    margin-bottom: 10rpx;

    .speed-control {
      display: flex;
      align-items: center;
      gap: 15rpx;
    }

    .speed-text {
      padding: 5rpx 10rpx;
      border: 1px solid #ddd;
      border-radius: 8rpx;
      font-size: 22rpx;
    }

    .extrButton {
      font-size: 22rpx;
      color: #007aff;
      padding: 5rpx 10rpx;
    }
  }

  .audio-slider {
    width: 100%;
    /* 可以根据需要调整进度条颜色 */
    /* 例如: #007aff */
  }
}
</style>